package com.study.experiment08.dao.impl;

import com.study.experiment08.dao.IUserDao;
import com.study.experiment08.model.User;
import org.springframework.orm.hibernate5.HibernateTemplate;

import java.util.List;

/**
 * @author WS
 */
public class UserDaoImp implements IUserDao {
    private HibernateTemplate hibTemplate;

    public void setHibTemplate(HibernateTemplate hibTemplate) {
        this.hibTemplate = hibTemplate;
    }

    @Override
    public Boolean find(User user) {
        Boolean result = false;
        String hql = "from User where username=? and password=?";
        List<User> list = (List<User>) hibTemplate.find(hql, new String[]{user.getUsername(), user.getPassword()});
        if (list.size() >= 1) {
            result = true;
        }
        return result;
    }

    // 查找指定用户
    @Override
    public User findUserByName(String username) {
        User user = null;
        String hql = "from User where username=?";
        List<User> list = (List<User>) hibTemplate.find(hql, username);
        if (list.size() >= 1) {
            user = list.get(0);
        }
        return user;
    }

    // 以ID查找用户
    @Override
    public User find(int id) {
        User user = null;
        String hql = "from User where id=?";
        List<User> list = (List<User>) hibTemplate.find(hql, new Integer(id));
        if (list.size() >= 1) {
            user = list.get(0);
        }
        return user;
    }

    // 查找所有用户
    @Override
    public List<User> findAll() {
        String hql = "from User";
        List<User> list = (List<User>) hibTemplate.find(hql);

        return list;
    }

    // 添加用户
    @Override
    public Boolean insert(User user) {
        Boolean result = false;
        if (findUserByName(user.getUsername()) == null) {
            hibTemplate.save(user);
            result = true;
        } else {
            System.out.println("User is exist!");
        }
        return result;
    }

    // 更新（修改）用户
    @Override
    public Boolean update(int id, User user) {
        hibTemplate.update(user);
        return true;
    }

    // 删除指定用户
    @Override
    public Boolean delete(int id) {
        User user = find(id);
        if (user != null) {
            hibTemplate.delete(user);
        }
        return true;
    }

}
